package com.qiuzhao.config;

import org.springframework.ai.openai.api.OpenAiApi;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.retry.policy.SimpleRetryPolicy;
import org.springframework.retry.support.RetryTemplate;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.netty.http.client.HttpClient;

import java.time.Duration;

@Configuration
public class OpenAiConfig {
    @Value("${spring.ai.openai.api-key}")
    private String apiKey;
    @Value("${spring.ai.openai.base-url}")
    private String baseUrl;

    @Bean
    public RetryTemplate openAiRetryTemplate() {
        RetryTemplate template = new RetryTemplate();
        // 可以设置最大重试次数
        template.setRetryPolicy(new SimpleRetryPolicy(3)); // 0 表示不重试
        return template;
    }
    @Bean
    public OpenAiApi openAiApi() {
        // 创建带超时的 HttpClient
        HttpClient httpClient = HttpClient.create()
                .responseTimeout(Duration.ofSeconds(60)) // 读超时
                .option(io.netty.channel.ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000); // 连接超时 10 秒


        return OpenAiApi.builder()
                .webClientBuilder(WebClient.builder()
                        .clientConnector(new org.springframework.http.client.reactive.ReactorClientHttpConnector(httpClient))
                )
                .apiKey(apiKey)
                .baseUrl(baseUrl)
                .build();
    }
}
